package temp;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.AudioFormat.Encoding;
import javax.sound.sampled.DataLine.Info;

public class MediaPlayer implements Runnable{

	private MediaPacketReceiver mediaPacketReceiver;
	
	private SourceDataLine	line ;
	private DataLine.Info	info ;
	private NewFormat audioFormat;
	
	
				
	public MediaPlayer(MediaPacketReceiver mediaPacketReceiver, ConnectionDescription connectionDescription) {
		try {
			
			this.audioFormat = connectionDescription.getAudioFormat();
			this.mediaPacketReceiver = mediaPacketReceiver;
			
			AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,audioFormat.getSampleRate(),audioFormat.getSampleSizeInBits(),audioFormat.getNumChannels()
					,audioFormat.getFrameSize(),audioFormat.getFrameRate(),audioFormat.isBigEndian());
			info = new Info(SourceDataLine.class, format);
			line = (SourceDataLine) AudioSystem.getLine(info);
			line.open(format);
			line.start();
			
			
		} catch (LineUnavailableException e) {
			e.printStackTrace();
		}
	}



	public void run() {
		line.start();
		int nBytesWrited = 0;
		try {
			Thread.sleep(500);//atraso inicial
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		while(nBytesWrited > -1){
			try {
				byte[] payload = mediaPacketReceiver.read();
				nBytesWrited = line.write(payload,0,payload.length);
				Thread.sleep(10);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
}
